
import Foundation
import Alamofire
import HandyJSON



class APICenter {

    
    static var appName = ""
    static let hots = ""
    
    static let foodUrl = "https://apis.tianapi.com/imgnutrient/index"
    

    static let dateFormatter: DateFormatter = {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        return dateFormatter
    }()
    
    enum Event: String {
        case open = "open"
        case sellpage = "sellpage"
        case buySuccess = "buy_success"
    }
    
    static func postEvent(event: Event) {        
        
        let subtype = appName
        
        let parameters = [
            "sub_type": subtype,
            "key": event.rawValue,
            "event_time": dateFormatter.string(from: Date()),
            "remark": "",
            "uid": "",
            "ip": "",
            "source": "ios",
            "version": Bundle.main.infoDictionary!["CFBundleShortVersionString"] as? String
        ]
        AF.request(hots, method: .post,parameters: parameters).responseJSON { (response) in
            print("埋点响应:", event, response)
        }
    }
    

    static func downloadFile(fileUrl:String, name:String, finish:((URL?) -> Void)?) {
            let hots = fileUrl
            let dest: DownloadRequest.Destination = { _, _ in
                let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
                let fileURL = documentsURL.appendingPathComponent(name)
                
                return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
            }
            
            AF.download(hots, interceptor: nil, to: dest).downloadProgress { (progress) in
                debugPrint("-------下载进度: \(progress.fractionCompleted)")
            }.responseData { res in
                if let data = res.fileURL {
                    if let finish = finish {
                        finish(data)
                        return
                    }
                }
                finish?(nil)
            }
        }


    static func foodQueryRequest(image: UIImage, result:((YunFoodModel?) -> Void)?, fail:((String) -> Void)?) {
        let base64 = image.jpegData(compressionQuality: 0.3)!.base64EncodedString()
        let pars = ["key":AppConfig.Food_Appkey, "img": base64]
        AF.request(foodUrl, method: .post, parameters: pars).responseJSON { response in
            print("food响应:", response)
            guard let json = response.value as? [String: Any] else{
                return
            }
            if let temp = ResponseModel.deserialize(from: json) {
                if !temp.result.list.isEmpty {
                    result?(temp.result.list[0])
                    return
                }
                fail?(temp.msg)
                return
            }
            fail?("未查询到相应信息")
        }
    }

    

    
}
